<?php
include_once("conn.php");

$email = stripslashes(trim($_POST['mail']));
$userid = stripslashes(trim($_POST['user_id']));

$email = injectChk($email);

$sql = "SELECT user_id,password FROM `users` WHERE email=:email AND user_id=:userid";
$stmt = $db->prepare($sql);
$stmt->execute(array(
    ':email' => $email,
    ':userid' => $userid
));
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if ($row) {
    $getpasstime = time();
//    $uid = $row['id'];
    $token = md5('as'.$row['user_id'] . $row['password'].'kl');
    $url = "http://47.94.216.86/lostpassword/reset.php?userid=".$row['user_id']."&email=" . $email . "&token=" . $token;
    $time = date('Y-m-d H:i');
    $result = sendmail($time, $email, $url);
    if ($result == 1) {//邮件发送成功
        $msg = '系统已向您的邮箱发送了一封邮件<br/>请登录到您的邮箱及时重置您的密码！';
        //更新数据发送时间
        $sql_update = "UPDATE `users` SET getpasstime=:getpasstime WHERE user_id=:user_id AND email=:email";
        $stmt_update = $db->prepare($sql_update);
        $stmt_update->execute(array(
            ':email' => $email,
            ':user_id' => $row['user_id'],
            ':getpasstime' => $getpasstime
        ));
    } else {
        $msg = $result;
    }
    echo $msg;
} else {
    echo 'noreg';
}

function sendmail($time, $email, $url)
{
    include_once("Smtp.class.php");
    $smtpserver = "ssl://smtp.163.com"; //SMTP服务器
    $smtpserverport = 465; //SMTP服务器端口
    $smtpusermail = "chinasdsxwx@163.com"; //SMTP服务器的用户邮箱
    $smtpuser = "chinasdsxwx@163.com"; //SMTP服务器的用户帐号
    $smtppass = "wangxu2018"; //SMTP服务器的用户密码
    $smtp = new Smtp($smtpserver, $smtpserverport, true, $smtpuser, $smtppass); //这里面的一个true是表示使用身份验证,否则不使用身份验证.
    $emailtype = "HTML"; //信件类型，文本:text；网页：HTML
    $smtpemailto = $email;
    $smtpemailfrom = $smtpusermail;
    $emailsubject = "YTU-hustoj - 找回密码";
    $emailbody = "亲爱的" . $email . "：<br/>您在" . $time . "提交了找回密码请求。请点击下面的链接重置密码（按钮24小时内有效）。<br/><a href='" . $url . "' target='_blank'>" . $url . "</a><br/>如果以上链接无法点击，请将它复制到你的浏览器地址栏中进入访问。<br/>如果您没有提交找回密码请求，请忽略此邮件。";
    $rs = $smtp->sendmail($smtpemailto, $smtpemailfrom, $emailsubject, $emailbody, $emailtype);
    return $rs;
}

function injectChk($sql_str)
{ //防止注入
    $check = preg_match('/select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/', $sql_str);
    if ($check) {
        echo('非法字符串');
        exit ();
    } else {
        return $sql_str;
    }
}

?>
